import $ from 'jquery';
import Button from './Button';
import Popover from '../Popover';

let slice = Array.prototype.slice; 

export default class LinkButton extends Button {

  render() {
    let args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    super.render.apply(this, args);
    return this.popover = new LinkPopover({button: this});
  }

  _status() {
    super._status();
    if (this.active && !this.editor.selection.rangeAtEndOf(this.node)) {
      return this.popover.show(this.node);
    } else {
      return this.popover.hide();
    }
  }

  command() {
    let $contents, $link, $newBlock, linkText, range, txtNode;
    range = this.editor.selection.range();
    if (this.active) {
      txtNode = document.createTextNode(this.node.text());
      this.node.replaceWith(txtNode);
      range.selectNode(txtNode);
    } else {
      $contents = $(range.extractContents());
      linkText = this.editor.formatter.clearHtml($contents.contents(), false);
      $link = $('<a/>', {
        href: 'http://www.example.com',
        target: '_blank',
        text: linkText || this._t('linkText')
      });
      if (this.editor.selection.blockNodes().length > 0) {
        range.insertNode($link[0]);
      } else {
        $newBlock = $('<p/>').append($link);
        range.insertNode($newBlock[0]);
      }
      range.selectNodeContents($link[0]);
      this.popover.one('popovershow', ((_this => () => {
        if (linkText) {
          _this.popover.urlEl.focus();
          return _this.popover.urlEl[0].select();
        } else {
          _this.popover.textEl.focus();
          return _this.popover.textEl[0].select();
        }
      }))(this));
    }
    this.editor.selection.range(range);
    return this.editor.trigger('valuechanged');
  }
}

LinkButton.prototype.name = 'link';
LinkButton.prototype.icon = 'link';
LinkButton.prototype.htmlTag = 'a';
LinkButton.prototype.disableTag = 'pre';

class LinkPopover extends Popover {

  render() {
    let tpl;
    tpl = `<div class="link-settings">\n  <div class="settings-field">\n    <label>${this._t('linkText')}</label>\n    <input class="link-text" type="text"/>\n    <a class="btn-unlink" href="javascript:;" title="${this._t('removeLink')}"\n      tabindex="-1">\n      <span class="simditor-icon simditor-icon-unlink"></span>\n    </a>\n  </div>\n  <div class="settings-field">\n    <label>${this._t('linkUrl')}</label>\n    <input class="link-url" type="text"/>\n  </div>\n  <div class="settings-field">\n    <label>${this._t('linkTarget')}</label>\n    <select class="link-target">\n      <option value="_blank">${this._t('openLinkInNewWindow')} (_blank)</option>\n      <option value="_self">${this._t('openLinkInCurrentWindow')} (_self)</option>\n    </select>\n  </div>\n</div>`;
    this.el.addClass('link-popover').append(tpl);
    this.textEl = this.el.find('.link-text');
    this.urlEl = this.el.find('.link-url');
    this.unlinkEl = this.el.find('.btn-unlink');
    this.selectTarget = this.el.find('.link-target');
    this.textEl.on('keyup', ((_this => e => {
      if (e.which === 13) {
        return;
      }
      _this.target.text(_this.textEl.val());
      return _this.editor.inputManager.throttledValueChanged();
    }))(this));
    this.urlEl.on('keyup', ((_this => e => {
      let val;
      if (e.which === 13) {
        return;
      }
      val = _this.urlEl.val();
      if (!(/https?:\/\/|^\//ig.test(val) || !val)) {
        val = `http://${val}`;
      }
      _this.target.attr('href', val);
      return _this.editor.inputManager.throttledValueChanged();
    }))(this));
    $([this.urlEl[0], this.textEl[0]]).on('keydown', ((_this => e => {
      let range;
      if (e.which === 13 || e.which === 27 || (!e.shiftKey && e.which === 9 && $(e.target).hasClass('link-url'))) {
        e.preventDefault();
        range = document.createRange();
        _this.editor.selection.setRangeAfter(_this.target, range);
        _this.hide();
        return _this.editor.inputManager.throttledValueChanged();
      }
    }))(this));
    this.unlinkEl.on('click', ((_this => e => {
      let range;
      let txtNode;
      txtNode = document.createTextNode(_this.target.text());
      _this.target.replaceWith(txtNode);
      _this.hide();
      range = document.createRange();
      _this.editor.selection.setRangeAfter(txtNode, range);
      return _this.editor.inputManager.throttledValueChanged();
    }))(this));
    return this.selectTarget.on('change', ((_this => e => {
      _this.target.attr('target', _this.selectTarget.val());
      return _this.editor.inputManager.throttledValueChanged();
    }))(this));
  }

  show() {
    let args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    super.show.apply(this, args);
    this.textEl.val(this.target.text());
    return this.urlEl.val(this.target.attr('href'));
  }
}
